<template>
    <div class="comment-item-wrap">
        <div class="left">
            <img class="user-img" :src="comment?.icon || config.defaultImg" alt="">
        </div>
        <div class="right">
            <el-row>
                <el-col :span="20">
                    <p class="name">{{comment?.userName || '暂无用户名'}}</p>
                    <p class="place">{{comment.schoolName || ''}}</p>
                </el-col>
                <el-col :span="4" class="flex-end">
                    <p class="time" v-if="comment?.gmtCreate">{{ dealDynamicTime(comment?.gmtCreate) }}</p>
                </el-col>
            </el-row>
            <p class="content">{{comment?.content}}</p>
            <div class="bottom-content">
                <!-- 点赞 -->
                <span class="count-item star" @click="addLike(comment)">
                    <img v-show="comment.like == 0" src="@/assets/img/comment/like.png" alt="">
                    <img v-show="comment.like == 1" src="@/assets/img/comment/liked.png" alt="">
                    <span>{{comment.likeNum}}</span>
                </span>
                <!-- 评论 -->
                <span class="count-item comment-icon" @click="handleComment">
                    <img v-show="!comment.showReply" src="@/assets/img/comment/comment.png" alt="">
                    <img v-show="comment.showReply" src="@/assets/img/comment/commented.png" alt="">
                    <span>{{comment.replyNum}}</span>
                </span>
                <!-- 展开评论框 -->
                <el-button
                    class="srt-el-button--link count-item btn"
                    @click="comment.showReplyInput = !comment.showReplyInput" 
                    link
                >
                    {{comment.showReplyInput ? '取消回复' : '回复'}}
                </el-button>
                <!-- 删除评论 -->
                <el-button v-if="isCreater || isCurrentUser" class="srt-el-button--link count-item btn" @click="onDelete(comment, 'comment')" link>删除</el-button>
            </div>
            <!-- 回复输入框 -->
            <div class="reply-input" v-show="comment.showReplyInput">
                <add-reply 
                    :parent-data="comment" 
                    @update:list="updateReply" 
                    :placeholder="`回复 @${comment?.userName || ''}`"
                    :visible="comment.showReplyInput"
                    :isPreview="isPreview"
                />
            </div>
            <!-- 回复list -->
            <div class="reply-warp" v-show="comment.showReply && comment.replyList && comment.replyList.length">
                <div class="comment-item-wrap reply-list" v-for="(reply, index) in comment.replyList || []" :key="index">
                    <div class="left">
                        <img class="user-img" :src="reply?.icon || config.defaultImg" alt="">
                    </div>
                    <div class="right reply-right" :class="{'no-border': index == comment.replyList.length - 1}">
                        <el-row>
                            <el-col :span="20">
                                <p class="name">{{reply?.userName || '暂无用户名'}}</p>
                                <p class="place">{{comment.schoolName || ''}}</p>
                            </el-col>
                            <el-col :span="4" class="flex-end">
                                <p class="time" v-if="reply?.gmtCreate">{{ dealDynamicTime(reply?.gmtCreate) }}</p>
                            </el-col>
                        </el-row>
                        <p class="content">{{reply?.content}}</p>
                        <div class="bottom-content">
                            <span class="count-item star" @click="addLike(reply)">
                                <img v-show="reply.like == 0" src="@/assets/img/comment/like.png" alt="">
                                <img v-show="reply.like == 1" src="@/assets/img/comment/liked.png" alt="">
                                <span>{{reply.likeNum}}</span>
                            </span>
                            <!-- 删除回复 -->
                            <el-button v-if="isCreater || isCurrentUserReply(reply)" class="srt-el-button--link count-item btn" @click="onDelete(reply, 'reply')" link>删除</el-button>
                        </div>
                    </div>
                </div>
                <div class="load-more" @click="loadMoreReply" v-show="comment.hasMoreReply">
                    <img src="~@/assets/img/comment/load-more-icon.png" alt="">
                    <span>展开讨论</span>
                </div>
            </div>

        </div>
    </div>
</template>

<script setup>
import config from '@/global/config';
import { dealDynamicTime, queryToJson } from '@/lib/tools';
import Confirm from '@/components/confirm/confirm.js';
import { useStore } from 'vuex';
import { computed, reactive } from 'vue';
import AddReply from './add-reply.vue'
import { useRoute } from 'vue-router';

const route = useRoute();

const store= useStore();

const emit = defineEmits(['update:list']);

const props = defineProps({
    data: {
        type: Object,
        default: () => {}
    },
    isCreater: {
        type: Boolean,
        default: false
    },
    isBuyPerson: {
        type: Boolean,
        default: false
    },
    index: {
        type: Number,
        default: 0
    },
    isPreview: { // 是否是预览状态
        type: Boolean,
        default: false
    }
});

// 回复列表参数
const replyListParams = reactive({
    page: 1,
    pageSize: 5,
    hasMore: false
})

// 当前用户信息
const currentUser = computed(() => {
    return store.state.currentUser || {};
})

// 是否是当前用户
const isCurrentUser = computed(() => {
    return currentUser.value?.userId && comment.value?.userId && currentUser.value.userId=== comment.value.userId;
})

const comment = computed(() => props.data)

function isCurrentUserReply(data){
    return currentUser.value?.userId && data?.userId && currentUser.value.userId == data.userId;
}

// 点赞、取消点赞
function addLike(data){
    let api = data.like == 0 ? 'addLike' : 'cancleLike'
    G_transmit(api, {
        data: {
            bizId: data.id,
            bizSource: 'moocComment',
        }
    }).then((res) => {
        data.likeNum = data.like == 0 ? data.likeNum+=1 : data.likeNum-=1
        data.like = data.like == 0 ? 1 : 0
    })
}

// 显示回复
function handleComment(){
    if(!comment.value.replyNum) return
    comment.value.showReply = !comment.value.showReply
    if(!comment.value.showReply){
        return
    }
    comment.value.replyList = []
    replyListParams.page = 1
    comment.value.hasMoreReply = true
    getReply(comment.value)
}

// 更新回复
function updateReply(type){
    replyListParams.page = 1
    comment.value.replyList = []
    type == 'add' ? comment.value.replyNum++ : comment.value.replyNum--
    comment.value.showReplyInput = false
    getReply(comment.value, true)
}

// 加载更多回复
function loadMoreReply(){
    replyListParams.page++
    getReply(comment.value)
}

// 获取评论的所有回复列表
function getReply (data = {}, show) {
    let catalogueId = queryToJson().catalogueId;
    G_transmit('commentListByCatalogue', {
        queries: {
            bizId: catalogueId, // 课件id
            bizSource: 'mooc', // 主体来源
            commentLevel: data.commentLevel != 2 ? 2 : 3, // 层级(1:一级评论, 2:二级评论 n:n级评论）
            pageIndex: replyListParams.page, // 第几页
            pageSize: replyListParams.pageSize, // 页面大小 （只有在pageSize=20 的条件下才能使用缓存）
            parentSource: route.params.moocId, // 慕课id
            parentCommentId: data.id, // # 父级评论ID 一级评论传0
            topParentCommentId: data.id,
            operationBizSource: 'moocComment'
        }
    }).then((res) => {
        if((data.replyList?.length || 0) <= res.data.total){
            data.replyList = [...(data.replyList || []), ...(res?.data?.rows || [])];
        }
        if (data.replyList.length >= res?.data?.total) {
			data.hasMoreReply = false;
		}
        if(show){
            comment.value.showReply = show && data.replyList.length > 0
        }
    }).finally(() => {
        // bottomLoading.value = false;
    })
}

// 删除讨论 预览状态下不能删除评论
function onDelete (data, type) {
    if (!data.id) {
        return
    }
    if (props.isPreview) {
        G_dispatchEvent('toast', { message: '预览状态下不可操作', type: 'error'});
        return
    }
    Confirm({
        title: '确认删除',
        text: `确定要删除此${type == 'comment' ? '讨论' : '回复'}吗？`
    }).then(ret => {
         G_transmit('deleteCatalogueComment', {
            data: {
                id: data.id
            }
        }).then((res) => {
            G_dispatchEvent('toast', { message: '操作成功', type: 'success'});
            if(type == 'comment'){
                emit('update:list');
            }else{
                updateReply('delete')
            }
        }).catch(_err => {
            console.log(_err);
        })
       
    }).catch(err => {
        // 点击取消按钮触发
        if (err === 'cancel') {
          return false
        }
    })
}
</script>

<style lang="scss" scoped>
.comment-item-wrap {
    display: flex;
    font-size: 14px;
    font-family: MicrosoftYaHei;
    padding: 20px 0 0;
    .left {
        width: 52px;
        margin-right: 14px;
        .user-img {
            width: 52px;
            height: 52px;
            border-radius: 50%;
        }
    }
    .right {
        flex: 1;
        border-bottom: 1px solid #E0E2E4;
        .flex-end {
            display: flex;
            justify-content: flex-end;
            align-items: flex-start;
        }
        .name {
            margin-top: 6px;
            color: var(--srt-main-text-color);
            line-height: 14px;
        }
        .place{
            font-size: 14px;
            color: #999999;
            line-height: 14px;
            margin-bottom: 17px;
            margin-top: 12px;
        }
        .content {
            color: var(--srt-main-text-color);
            line-height: 21px;
            word-break: break-all;
            margin-bottom: 15px;
        }
        .bottom-content{
            display: flex;
            align-items: center;
            justify-content: flex-start;
            margin-bottom: 18px;
            .count-item{
                font-size: 14px;
                color: #999999;
                margin-right: 20px;
                margin-left: 0;
                display: inline-flex;
                align-items: center;
                cursor: pointer;
                img{
                    width:14px;
                    height:14px;
                    margin-right: 6px;
                }
            }
        }
        .time {
            color: var(--srt-color-light-gray);
            line-height: 19px;
            padding-bottom: 20px;
        }
    }
    
    &:last-child {
        .right {
            border-bottom: none;
        }
        .time {
            padding-bottom: 0;
        }
    }
}
.reply-warp{
    background: #F7F9FA;
    padding: 0 20px 24px;
    box-sizing: border-box;
    position: relative;
    margin-bottom:20px;
    border-radius: 4px;
    
    &::before{
        content: '';
        position: absolute;
        top:0;
        left:57px;
        width: 15px;
        height:15px;
        transform: rotate(45deg) translate(-50%,0);
        background: #F7F9FA;
    }
}
.no-border{
    border: none !important;
}
.more-popover-list {
    li {
        font-size: 14px;
        line-height: 32px;
        font-family: MicrosoftYaHei;
        color: var(--srt-main-text-color);
        text-align: center;
        cursor: pointer;
        &:hover {
            background: #E7F1FF;
            border-radius: 4px;
        }
    }
}
.handled{
    i{
        color: red;
    }
}
.load-more{
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #0084F6;
    line-height: 14px;
    margin-left:67px;
    cursor: pointer;
    img{
        margin-right: 6px;
        width:14px;
        height:14px;
    }
}
.btn{
    font-family: MicrosoftYaHei;
    font-weight: normal;
}
</style>

<style lang="scss">
.more-popover {
    min-width: 74px!important;
    right: -8px!important;
    top: -9px!important;
    padding: 6px !important;
    border: none!important;
    box-shadow: 0px 2px 6px 0px rgba(0, 0 ,0 , 0.1) !important;
    .el-popper__arrow {
        display: none;
    }
}
.more-option-btn {
    border: none;
    padding: none;
    color: var(--srt-main-text-color);
    .iconfont {
        &:hover {
            color: var(--srt-color-primary);
        }
    }
}
</style>